package cn.yunyichina.provider.bone.service.impl;

import cn.yunyichina.provider.bone.dao.SignApplicationDao;
import cn.yunyichina.provider.bone.entity.SignApplication;
import cn.yunyichina.provider.framework.dubbo.service.BaseService;
import cn.yunyichina.provider.framework.dubbo.service.CacheService;
import cn.yunyichina.provider.framework.page.PageInfo;
import cn.yunyichina.provider.framework.utils.UUIDUtil;
import cn.yunyichina.provider.iface.entity.common.Response;
import cn.yunyichina.provider.iface.entity.common.ResponseObject;
import cn.yunyichina.utils.commons.DateUtils;
import cn.yunyichina.utils.commons.MobileUtil;
import cn.yunyichina.utils.convert.JsonUtils;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author hezuzhi
 * @Description: (签约医生)
 * @date 2017/4/20  15:42.
 * @version: 1.0
 */
@Service
public class SignApplicationServiceImpl {
    private static final Logger logger = LoggerFactory.getLogger(SignApplicationServiceImpl.class);

    @Autowired
    private SignApplicationDao signApplicationDao;

    private final String UNIVERSAL_VERIFICATION = "360123"; //万能验证码

    /**
     * 签约医生提交 yyt.bone.sign.application.approve
     *
     * @param data
     * @return
     */
    public ResponseObject ApproveSignApplication(String data) {
        logger.info("ApproveSignApplication 请求参数data: " + data);
        SignApplication signApplication = null;
        if (StringUtils.isNotBlank(data)) {
            signApplication = JsonUtils.parseObject(data, SignApplication.class);
        }

        ResponseObject response = new ResponseObject();
        if (!StringUtils.isNotBlank(signApplication.getMobile())) {
            response.setResultCodeAndMessage("1001", "请求参数mobile 缺失");
            logger.info("ApproveSignApplication请求参数mobile 缺失");
            return response;
        }
        if (!MobileUtil.isPhoneNum(signApplication.getMobile())) {
            response.setResultCodeAndMessage("1001", "参数mobile 验证失败");
            logger.info("ApproveSignApplication请求参数mobile 验证失败" + signApplication.getMobile());
            return response;
        }
        if (!StringUtils.isNotBlank(signApplication.getUserName()) || StringUtils.isBlank(signApplication.getVerificationCode())) {
            response.setResultCodeAndMessage("1001", "请求参数user_name 或 verification_code  缺失");
            logger.info("ApproveSignApplication请求参数user_name 或 verification_code 缺失");
            return response;
        }

        //检查该医生是否已新增
        Map<String, String> map = new HashMap<String,String>();
        map.put("mobile" , signApplication.getMobile());
        map.put("enable_flag" , "1");
        Response userReps = BaseService.callHumpFromInternal("yyt.base.orguser.by.mobile.get", JsonUtils.toJsonString(map));
        if("0".equals(userReps.getResultCode())){
            logger.info("ApproveSignApplication 该医生已入驻平台！ json:" + JsonUtils.toJsonString(userReps));
            response.setResultCodeAndMessage("1999" , "您已经是仁医骨科平台的入驻医生，请直接前往登录。");
            return response;
        }


        //检查该医生是否已签约
        List<SignApplication> signApplications = signApplicationDao.select(signApplication);
        if(signApplications.size() > 0){
            logger.info("ApproveSignApplication 该医生已成功签约！ json:" + JsonUtils.toJsonString(signApplication));
            response.setResultCodeAndMessage("1999" , "您已提交申请，仁医正在审核，审核通过后将短信通知您！");
            return response;
        }


        // 从缓存中获取验证码
        String verificationCode = CacheService.getGlobalKey("base", "verification_code", signApplication.getMobile());
        logger.info("签约医生接口, 缓存中获取验证码为：" + verificationCode);

        if (StringUtils.isNotBlank(verificationCode) &&
                (verificationCode.trim().equalsIgnoreCase(signApplication.getVerificationCode().trim()))) {
            if (StringUtils.isNotBlank(signApplication.getIntroducerId())){
                Map<String ,String> introducerMessageRequest = new HashMap<>();
                introducerMessageRequest.put("user_id",signApplication.getIntroducerId());
                Response introducerMessageResponse  = BaseService.callHumpFromInternal("yyt.base.orguser.introducer.message.get", JsonUtils.toJsonString(introducerMessageRequest));
                if ("0".equals(introducerMessageResponse.getResultCode())){
                    JSONObject jsonObject = JSONObject.parseObject(introducerMessageResponse.getResult() );
                    signApplication.setIntroducerOrgId(jsonObject.getString("orgId"));
                    signApplication.setIntroducerOrgName(jsonObject.getString("orgName"));
                    signApplication.setIntroducerDeptId(jsonObject.getString("deptId"));
                    signApplication.setIntroducerDeptName(jsonObject.getString("deptName"));
                }
            }

            signApplication.setId(UUIDUtil.get32UUID());
            signApplication.setManageFlag((short) 0);//0未处理
            signApplication.setApplyTime(DateUtils.dateToString(new Date()));
            try {
                signApplicationDao.insert(signApplication);
                response.setResultObject(signApplication);
                logger.info("仁医---ApproveSignApplication签约医生提交完成");
            } catch (Exception e) {
                response.setResultCodeAndMessage("1", "调用失败");
                logger.error("仁医---ApproveSignApplication", e);

                response.setResultCodeAndMessage("1999", "签约医生提交失败");

            }
        }else{
            response.setResultCodeAndMessage("1999", "验证码有误！");
            return response;
        }

        return response;
    }

    /**
     * 签约医生列表 yyt.bone.sign.application.get
     *
     * @param data 根据id修改签约医生处理ManageFlag
     * @return
     */
    public Response getSignApplication(String data) {
        logger.info("getSignApplication 请求参数data: " + data);
        Map<String, Object> result = new HashMap<>();

        SignApplication signApplication = JsonUtils.parseObject(data, SignApplication.class);

        Map<String, String> maps = JsonUtils.parseObject(data, Map.class);

        PageInfo pageInfo = new PageInfo();
        if (maps.containsKey("page_size")) {
            pageInfo.setPageSize(Integer.valueOf(maps.get("page_size")));
        }
        if (maps.containsKey("page_num")) {
            pageInfo.setPageNum(Integer.valueOf(maps.get("page_num")));
        }

        Response response = new Response();
        try {
            //查出总记录数
            long count = signApplicationDao.selectCount(signApplication);

            pageInfo.setTotal(count);
            pageInfo.setPages((pageInfo.getTotal().intValue() + pageInfo.getPageSize() - 1) / pageInfo.getPageSize());
            List<SignApplication> signApplicationList = signApplicationDao.select(signApplication, pageInfo);

            result.put("list", signApplicationList);
            result.put("page_info", pageInfo);

            response.setResult(JsonUtils.toJsonString(result));
            response.setResultCodeAndMessage("0", "查询成功!");
            logger.info("仁医---getSignApplication签约医生列表获取成功");
        } catch (Exception e) {
            logger.error("仁医---getSignApplication", e);
            response.setResultCodeAndMessage("1999", "签约医生获取失败");

        }
        return response;
    }

    /**
     * 签约医生处理 yyt.bone.sign.application.update
     *
     * @param data 根据id修改签约医生处理ManageFlag
     * @return
     */
    public ResponseObject updateSignApplication(String data) {
        logger.info("updateSignApplication 请求参数data: " + data);
        Map<String, String> maps = JsonUtils.parseObject(data, Map.class);
        String id = maps.get("id");

        ResponseObject response = new ResponseObject();
        if (!StringUtils.isNotBlank(id)) {
            response.setResultCodeAndMessage("1001", "请求参数id 缺失");
            logger.info("仁医---updateSignApplication请求参数id 缺失");
            return response;
        }

        try {
            SignApplication signApplication = signApplicationDao.selectById(id);
            if (signApplication == null) {
                response.setResultCodeAndMessage("1001", "无此id专家" + id);
                logger.info("仁医---updateSignApplication请求参数id 缺失" + id);
                return response;
            }

            signApplication.setManageFlag((short) 1);//0未处理  1已处理

            signApplicationDao.update(signApplication);
            response.setResultObject("提交成功");
            logger.info("仁医---updateSignApplication签约医生修改完成");
        } catch (Exception e) {
            response.setResultCodeAndMessage("1", "提交失败");
            logger.error("仁医---updateSignApplication", e);

            response.setResultCodeAndMessage("1999", "签约医生修改失败");

        }

        return response;
    }
}
